package com.atguigu.publisher1.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.publisher1.service.ProductStatsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
public class SugarController {

    @Autowired
    private ProductStatsService productStatsService;

    @RequestMapping("/api/sugar/gmv")
    public String getGmv(@RequestParam(value = "date", defaultValue = "0") int date) {

        //如果外部没有传入时间参数,则默认返回今天的数据
        if (date == 0) {
            date = getToday();
        }

        //查询当日GMV数据
        BigDecimal gmv = productStatsService.getGmv(date);

        //封装JSON病返回
        String result = "{" +
                "  \"status\": 0," +
                "  \"msg\": \"\"," +
                "  \"data\": " + gmv + "" +
                "}";

//        HashMap<String, Object> result = new HashMap<>();
//        result.put("status", "0");
//        result.put("msg", "");
//        result.put("data", gmv);
//
//        return JSONObject.toJSONString(result);
        return result;

    }

    @RequestMapping("/api/sugar/tm")
    public String getGmvByTm(@RequestParam(value = "date", defaultValue = "0") int date,
                             @RequestParam(value = "limit", defaultValue = "5") int limit) {

        //1.如果没有传入时间,则默认返回今天的数据
        if (date == 0) {
            date = getToday();
        }

        //2.查询数据
        Map gmvByTm = productStatsService.getGmvByTm(date, limit);

        //3.分别取出key和value
        Set keys = gmvByTm.keySet();
        Collection values = gmvByTm.values();

        //4.拼接字符串
        return "{" +
                "  \"status\": 0," +
                "  \"msg\": \"\"," +
                "  \"data\": {" +
                "    \"categories\": [\"" +
                StringUtils.join(keys, "\",\"") +
                "\"]," +
                "    \"series\": [" +
                "      {" +
                "        \"name\": \"品牌\"," +
                "        \"data\": [" +
                StringUtils.join(values, ",") +
                "        ]" +
                "      }" +
                "    ]" +
                "  }" +
                "}";

    }

    private int getToday() {

        //获取今天时间
        long ts = System.currentTimeMillis();

        //格式化时间对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        return new Integer(sdf.format(ts));
    }

}
